package com.xiaoye.digitaltwin.easyexcel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.xiaoye.digitaltwin.entity.Student;
import com.xiaoye.digitaltwin.service.StudentService;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * Create by xiaoye on 2023/4/8
 */
@Slf4j
public class StudentListener implements ReadListener<Student> {

    /**
     *
     */
    private static final int BATCH_COUNT = 5;

    private List<Student> cachedStuList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    private StudentService studentService;

    public StudentListener(){

    }

    public StudentListener(StudentService studentService){
        this.studentService = studentService;
    }

    @Override
    public void invoke(Student student, AnalysisContext analysisContext) {
        cachedStuList.add(student);
        if (cachedStuList.size() >= BATCH_COUNT){
            saveData();
            cachedStuList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
        log.info("所有数据解析完成");
    }

    private void saveData(){
        studentService.saveBatch(cachedStuList);
    }
}
